package com.htiiot.hbase;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

/**
 * 
 * @author SunMy
 *
 */
public class HbaseClient {
	private static Configuration config = HBaseConfiguration.create();
	private static Admin hbaseAdmin = null;
	private static Connection hbaseConnect = null;
	
	
	public static void main(String[] args) {
		Cmd.parserCmd(args);
		config.set( "hbase.zookeeper.quorum",Cmd.zk );
		config.set( "zookeeper.znode.parent","/hbase-unsecure" );
		try {
			hbaseConnect = ConnectionFactory.createConnection(config);
			hbaseAdmin = hbaseConnect.getAdmin();
			String[] tableFa={"t"};
			String[] tableuidFa={"id","name"};
			createTable(Cmd.table, 256,tableFa);
			createTable(Cmd.uidTable, 1,tableuidFa);
			
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public static void createTable(String tableNameTSDB,int regionNum,String[] fas){
		
		TableName tableName = TableName.valueOf(tableNameTSDB );
		try {
			if (!hbaseAdmin.tableExists( tableName )) {
				HTableDescriptor tableDesc = new HTableDescriptor( tableName );
				for(String fs:fas){
					HColumnDescriptor familyDesc = new HColumnDescriptor( fs );
					tableDesc.addFamily( familyDesc );
				}
				if(regionNum>1){
					byte[][] splits = getRegion(regionNum);
					hbaseAdmin.createTable( tableDesc, splits );
				}else{
					hbaseAdmin.createTable( tableDesc);
				}
				System.out.println(tableNameTSDB+" create successful");
			}else{
				System.out.println("表"+tableNameTSDB+"已存在");
				System.exit(0);
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
	private static byte[][] getRegion(int regionNumber) {
		byte[][] splits = new byte[regionNumber - 1][];
		int step = 256 / regionNumber;
		for(int i = 0; i < regionNumber-1; i++){
			int num = 0;
			byte[] bytes = new byte[29];
			num = (i+1) * step;
			bytes[0]=(byte)num;
			splits[i] = bytes;
		}
		return splits;
	}
	
}
